#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <cstring>

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " filemame" << std::endl;
        return 1;
    }

    std::string filename = argv[1];

    int fd = ::open(filename.c_str(), O_RDONLY);
    if (fd < 0)
    {
        std::cerr << "open error" << std::endl;
        return 2;
    }

    // 获取文件真实大小
    struct stat st;
    ::fstat(fd, &st);
    char* mmap_addr = (char*)::mmap(nullptr, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if (mmap_addr == MAP_FAILED)
    {
        perror("mmap");
        return 3;
    }

    std::cout << mmap_addr << std::endl;

    // 取消映射
    ::munmap(mmap_addr, st.st_size);

    // 关闭文件
    ::close(fd);
    
    return 0;
}